package com.hellobike.haxing.modules.purchase.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hellobike.haxing.common.constant.CacheConstant;
import com.hellobike.haxing.common.util.RedisUtil;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.address.entity.TKV;
import com.hellobike.haxing.modules.address.util.Convert2KV;
import com.hellobike.haxing.modules.order.entity.OrderTimeConfig;
import com.hellobike.haxing.modules.order.mapper.OrderMapper;
import com.hellobike.haxing.modules.order.service.IOrderTimeConfigService;
import com.hellobike.haxing.modules.pms.purchaseSend.entity.TPurchaseSend;
import com.hellobike.haxing.modules.product.entity.Sku;
import com.hellobike.haxing.modules.product.entity.Spu;
import com.hellobike.haxing.modules.product.mapper.SkuMapper;
import com.hellobike.haxing.modules.product.mapper.SpuMapper;
import com.hellobike.haxing.modules.purchase.common.SnakeFakeId;
import com.hellobike.haxing.modules.purchase.common.TimerUtil;
import com.hellobike.haxing.modules.purchase.dto.TPurchaseOrderHeadDto;
import com.hellobike.haxing.modules.purchase.dto.TPurchaseProDto;
import com.hellobike.haxing.modules.purchase.entity.*;
import com.hellobike.haxing.modules.purchase.enums.OrderState;
import com.hellobike.haxing.modules.purchase.mapper.TPurchaseInfoMapper;
import com.hellobike.haxing.modules.purchase.mapper.TPurchaseOrderDetailMapper;
import com.hellobike.haxing.modules.purchase.mapper.TPurchaseOrderMapper;
import com.hellobike.haxing.modules.purchase.mapper.TPurchaseProMapper;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseProRecordService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseProService;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClPro;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClassification;
import com.hellobike.haxing.modules.supplier.entity.TSupplierInfo;
import com.hellobike.haxing.modules.supplier.mapper.TSupplierClProMapper;
import com.hellobike.haxing.modules.supplier.mapper.TSupplierClassificationMapper;
import com.hellobike.haxing.modules.supplier.mapper.TSupplierInfoMapper;
import com.hellobike.haxing.modules.supplier.util.BeanUtils;
import com.hellobike.haxing.modules.supplier.util.Constant;
import com.hellobike.haxing.modules.supplier.util.Convert;
import com.hellobike.haxing.modules.wms.entity.AsnDetail;
import com.hellobike.haxing.modules.wms.entity.AsnHeader;
import com.hellobike.haxing.modules.wms.entity.Warehouse;
import com.hellobike.haxing.modules.wms.facade.WmsReceiveFacade;
import com.hellobike.haxing.modules.wms.mapper.WarehouseMapper;
import com.hellobike.haxing.modules.wms.service.IWarehouseService;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * @Description: 商品列表
 * @Author: haxing-boot
 * @Date: 2020-01-20
 * @Version: V1.0
 */
@Service
@Slf4j
public class TPurchaseProServiceImpl extends ServiceImpl<TPurchaseProMapper, TPurchasePro> implements ITPurchaseProService {

    @Autowired
    private TPurchaseProMapper tPurchaseProMapper;
    @Autowired
    private TPurchaseOrderMapper tPurchaseOrderMapper;
    @Autowired
    private TPurchaseOrderDetailMapper tPurchaseOrderDetailMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private TPurchaseInfoMapper tPurchaseInfoMapper;

    @Autowired
    private TSupplierInfoMapper tSupplierInfoMapper;

    @Autowired
    private WmsReceiveFacade wmsReceiveFacade;

    @Autowired
    private IWarehouseService iWarehouseService;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private TSupplierClProMapper tSupplierClProMapper;

    @Autowired
    private TSupplierClassificationMapper tSupplierClassificationMapper;

    @Autowired
    private ITPurchaseProRecordService itPurchaseProRecordService;


    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private SnakeFakeId snakeFakeId;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void test() {
        TPurchaseProDto tPurchaseProDto = new TPurchaseProDto();
        tPurchaseProDto.setPurchaseVolume(100);
        tPurchaseProDto.setSkuId(209L);
        tPurchaseProDto.setType(1);
        syncProFromOrder(tPurchaseProDto);
    }

    @Override
    public Result<?> syncProFromOrder(TPurchaseProDto tPurchaseProDto) {
        log.info("同步订单到采购单接收信息=step1=orderCode={}==dto={}", tPurchaseProDto.getOrderCode(), JSON.toJSONString(tPurchaseProDto));
        Object redisOrderId = redisUtil.get(CacheConstant.ORADER_SUCCESS_MQ_ORDERID + ":tmp:" + tPurchaseProDto.getSkuId());
        if (redisOrderId != null) {
            log.error("=支付成功订单同步采购单MQ重复消费==订单ID={}==", tPurchaseProDto.getSkuId());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        redisUtil.set(CacheConstant.ORADER_SUCCESS_MQ_ORDERID + ":tmp:" + tPurchaseProDto.getSkuId(), "1", 1);
        try {
            if (tPurchaseProDto.getSkuId() == null && tPurchaseProDto.getPurchaseVolume() < 1) {
                return Result.error("skuId is null");
            }
            if (tPurchaseProDto.getOrderTime() == null) {
                return Result.error("orderTime is null");
            }

            LambdaQueryWrapper<TPurchasePro> queryWrapper = new QueryWrapper<TPurchasePro>().lambda();
            queryWrapper.eq(TPurchasePro::getSkuId, tPurchaseProDto.getSkuId());
            List<OrderTimeConfig> orderTimeConfigList = orderTimeConfigService.getBaseMapper().selectList(null);
            OrderTimeConfig orderTimeConfig = null;
            if (!CollectionUtils.isEmpty(orderTimeConfigList)) {
                for (OrderTimeConfig timeConfig : orderTimeConfigList) {
                    if (timeConfig.getType() == 0) {
                        orderTimeConfig = timeConfig;
                    }
                }
            }
            log.info("order-time-config:{}", JSON.toJSONString(orderTimeConfig));
            /**
             * 判断结单时间，如果是当天，截单是是当天配置时间，如果时间大于时间点，时间是明天
             */
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime today = now.withHour(orderTimeConfig.getTime().getHours()).withMinute(orderTimeConfig.getTime().getMinutes())
                    .withSecond(0);
            if (now.getHour() > orderTimeConfig.getTime().getHours()) {
                today = today.plusDays(-1);
            }
            queryWrapper.ge(TPurchasePro::getCreateTime, today.plusDays(1)).le(TPurchasePro::getCreateTime, today);
            TPurchasePro tPurchasePro = tPurchaseProMapper.selectOne(queryWrapper);
            List<TSupplierInfo> supplierInfos = tSupplierInfoMapper.selectList(new QueryWrapper<TSupplierInfo>()
                    .lambda().eq(TSupplierInfo::getState, 4).eq(TSupplierInfo::getDeleted, 0));
            List<Long> idList = supplierInfos.stream().map(TSupplierInfo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<TSupplierClPro> queryWrapper1 = new QueryWrapper<TSupplierClPro>().lambda().eq(TSupplierClPro::getSkuId, tPurchaseProDto.getSkuId())
                    .orderByDesc(TSupplierClPro::getIsDefault).gt(TSupplierClPro::getSupplyVolume, 0).orderByDesc(TSupplierClPro::getSupplierId)
                    .eq(TSupplierClPro::getDeleted, 0);
            if (!CollectionUtils.isEmpty(idList)) {
                queryWrapper1.in(TSupplierClPro::getSupplierId, idList);
            }
            /**
             * 查询默认供应商
             */
            TSupplierClPro tSupplierClPro = tSupplierClProMapper.selectOne(queryWrapper1
                    .last("limit 1"));
            if (tPurchasePro != null) {
                tPurchasePro.setSupplierId(tSupplierClPro.getSupplierId());
                tPurchasePro.setSupplierName(tSupplierClPro.getSupplierName());
                tPurchasePro.setSupplyVolume(tSupplierClPro.getSupplyVolume());
                log.info("同步订单到采购单开始处理=step2=purchasePro={}", JSON.toJSONString(tPurchaseProDto));
                // 增加记录表
                setProRecord(tPurchasePro, tPurchaseProDto);
                TPurchasePro updateDo = new TPurchasePro();
                updateDo.setId(tPurchasePro.getId());
                if (tPurchasePro.getSupplyVolume() != null && updateDo.getPurchaseVolume() != null && tPurchasePro.getSupplyVolume() < updateDo.getPurchaseVolume()) {
                    updateDo.setIsMissingParts(Constant.IS_MISSING_PARTS_YES);
                    updateDo.setMissingPartsVolume(updateDo.getPurchaseVolume() - tPurchasePro.getSupplyVolume());
                }
                updateDo.setIsOrder(Constant.IS_ORDER_NO);

                if (tPurchaseProDto.getType().equals(Constant.IS_ORDER_YES)) {
                    if (tPurchasePro.getPurchaseVolume() != null) {
                        tPurchaseProMapper.updatePurchaseByAdd(updateDo.getId(), tPurchaseProDto.getPurchaseVolume(), updateDo.getIsOrder(), updateDo.getMissingPartsVolume(), updateDo.getIsMissingParts());
                    } else {
                        updateDo.setPurchaseVolume(tPurchaseProDto.getPurchaseVolume());
                        tPurchaseProMapper.updateById(updateDo);
                    }

                } else {
                    if (tPurchasePro.getPurchaseVolume() != null) {
                        tPurchaseProMapper.updatePurchaseBySub(updateDo.getId(), tPurchaseProDto.getPurchaseVolume(), updateDo.getIsOrder(), updateDo.getMissingPartsVolume(), updateDo.getIsMissingParts());
                    } else {
                        updateDo.setPurchaseVolume(tPurchaseProDto.getPurchaseVolume());
                        tPurchaseProMapper.updateById(updateDo);
                    }
                }
                createPurchaseInfo(tPurchasePro);
            } else {
                tPurchasePro = new TPurchasePro();
                tPurchasePro.setPurchaseVolume(tPurchaseProDto.getPurchaseVolume());
                tPurchasePro.setDateDue(tSupplierClPro.getDateDue());
                tPurchasePro.setDeleted(0);
                tPurchasePro.setDimensionValues(tSupplierClPro.getDimensionValues());
                tPurchasePro.setIsMissingParts(0);
                tPurchasePro.setIsOrder(0);
                tPurchasePro.setPurchasePrice(tSupplierClPro.getPurchasePrice());
                tPurchasePro.setSkuId(tSupplierClPro.getSkuId());
                tPurchasePro.setSkuName(tSupplierClPro.getSkuName());
                tPurchasePro.setSkuUnit(tSupplierClPro.getSkuUnit());
                tPurchasePro.setWarehouseId(tPurchaseProDto.getWarehouseId());
                tPurchasePro.setCreateTime(new Date());
                tPurchasePro.setUpdateTime(new Date());
                tPurchasePro.setSupplyVolume(tSupplierClPro.getSupplyVolume());
                tPurchasePro.setSupplierId(tSupplierClPro.getSupplierId());
                Warehouse warehouse = warehouseMapper.selectById(tPurchaseProDto.getWarehouseId());
                if (warehouse != null) {
                    tPurchasePro.setWarehouseName(warehouse.getWarehouseName());
                }
                tPurchasePro.setSupplierName(tSupplierClPro.getSupplierName());
                if (tPurchasePro.getPurchaseVolume() == null || tPurchasePro.getPurchaseVolume() < 1) {
                    tPurchasePro.setSupplyVolume(1000);
                }
                tPurchaseProMapper.insert(tPurchasePro);
                createPurchaseInfo(tPurchasePro);
            }
        } catch (Exception e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("success");
    }

    private void setProRecord(TPurchasePro tPurchasePro, TPurchaseProDto tPurchaseProDto) {
        TPurchaseProRecord tPurchaseProRecord = new TPurchaseProRecord();
        BeanUtils.copyProperties(tPurchasePro, tPurchaseProRecord);
        tPurchaseProRecord.setPurchaseVolume(tPurchaseProDto.getPurchaseVolume());
        tPurchaseProRecord.setType(tPurchaseProDto.getType());
        tPurchaseProRecord.setOrderCode(tPurchaseProDto.getOrderCode());
        tPurchaseProRecord.setOrderTime(tPurchaseProDto.getOrderTime());
        tPurchaseProRecord.setCreateTime(new Date());
        tPurchaseProRecord.setUpdateTime(new Date());
        tPurchaseProRecord.setId(snakeFakeId.nextId());
        itPurchaseProRecordService.save(tPurchaseProRecord);
    }

    // 创建采购信息汇总
    public boolean createPurchaseInfo(TPurchasePro tPurchasePro) {
        if (tPurchasePro.getWarehouseId() != null) {
            QueryWrapper<TPurchaseInfo> info = new QueryWrapper<>();
            info.eq("warehouse_id", tPurchasePro.getWarehouseId());
            info.eq("supplier_id", tPurchasePro.getSupplierId());
            info.eq("is_missing_parts", Constant.IS_MISSING_PARTS_NO);
            LocalDateTime dateTime = LocalDateTime.now();
            if (dateTime.getHour() > 23) {
                info.ge("create_time", TimerUtil.getcurrent23Date());
            } else {
                info.ge("create_time", TimerUtil.getLast23Date());
                info.le("create_time", TimerUtil.getcurrent23Date());
            }

            info.orderByDesc("create_time");
            info.last("limit 1");
            TPurchaseInfo tPurchaseInfo = tPurchaseInfoMapper.selectOne(info);
            if (tPurchaseInfo == null) { // 当前一批 汇总表没有信息
                TPurchaseInfo infoDo = new TPurchaseInfo();
                infoDo.setSupplierId(tPurchasePro.getSupplierId());
                infoDo.setSupplierName(tPurchasePro.getSupplierName());
                infoDo.setWarehouseId(tPurchasePro.getWarehouseId());
                if (tPurchasePro.getWarehouseId() != null && infoDo.getWarehouseName() == null) {
                    Warehouse warehouse = warehouseMapper.selectById(tPurchasePro.getWarehouseId());
                    try {
                        infoDo.setWarehouseName(warehouse.getWarehouseName());
                    } catch (Exception ex) {
                        log.error("", ex);
                    }
                }
                infoDo.setIsMissingParts(Constant.IS_MISSING_PARTS_NO);
                infoDo.setCreateTime(new Date());
                infoDo.setCreateBy(1);
                infoDo.setDeleted(0);
                tPurchaseInfoMapper.insert(infoDo);
            } else {
                QueryWrapper<TPurchasePro> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("is_order", Constant.IS_ORDER_NO);
                queryWrapper.eq("supplier_id", tPurchasePro.getSupplierId());
                queryWrapper.eq("warehouse_id", tPurchasePro.getWarehouseId());
                queryWrapper.gt("purchase_volume", 0);
                List<TPurchasePro> tPurchaseProList = tPurchaseProMapper.selectList(queryWrapper);
                if (ListUtil.isNullOrEmpty(tPurchaseProList)) {
                    tPurchaseInfo.setIsMissingParts(Constant.IS_MISSING_PARTS_YES);
                    tPurchaseInfo.setUpdateTime(new Date());
                    tPurchaseInfoMapper.updateById(tPurchaseInfo);
                }
            }
            return true;
        } else {
            return false;
        }
    }

    @Autowired
    private IOrderTimeConfigService orderTimeConfigService;


    @Override
    public void getAllPro() {
        List<OrderTimeConfig> orderTimeConfigList = orderTimeConfigService.getBaseMapper().selectList(null);
        OrderTimeConfig orderTimeConfig = null;
        if (!CollectionUtils.isEmpty(orderTimeConfigList)) {
            for (OrderTimeConfig timeConfig : orderTimeConfigList) {
                if (timeConfig.getType() == 0) {
                    orderTimeConfig = timeConfig;
                }
            }
        }
        log.info("order-time-config:{}", JSON.toJSONString(orderTimeConfig));
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime today = now.withHour(orderTimeConfig.getTime().getHours()).withMinute(orderTimeConfig.getTime().getMinutes())
                .withSecond(0);
        if (now.getHour() < orderTimeConfig.getTime().getHours()) {
            today = today.plusDays(-1);
        }
        QueryWrapper<TPurchaseInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("is_missing_parts", Constant.IS_ORDER_YES);
        queryWrapper.ge("create_time", today.plusDays(-1));
        queryWrapper.le("create_time", today);
        List<TPurchaseInfo> tPurchaseInfos = tPurchaseInfoMapper.selectList(queryWrapper);
        if (tPurchaseInfos != null && tPurchaseInfos.size() > 0) {
            log.info("t_purchase_info:{}", JSON.toJSONString(tPurchaseInfos));
            for (TPurchaseInfo item : tPurchaseInfos) {
                if (item.getSupplierId() != null && item.getWarehouseId() != null) {
                    genAsnAndPo(item.getSupplierId(), item.getWarehouseId(), item.getCreateBy(), today.plusDays(-1));
                }
            }
        }
    }

    public void genAsnAndPo(Long supplierId, Long wareHouseId, Integer userId, LocalDateTime today) {
        try {
            List<TPurchasePro> tPurchaseProList = tPurchaseProMapper.selectSupplierPro(supplierId,wareHouseId,today.plusDays(1),today);
            if (ListUtil.isNotEmpty(tPurchaseProList)) {
                int purchaseVolume = 0;
                BigDecimal purchasePrice = new BigDecimal(0);
                for (TPurchasePro tPurchasePro : tPurchaseProList) {
//                    if (tPurchasePro.getPurchaseVolume() != null && tPurchasePro.getPurchasePrice() != null) {
                    try {
                        Integer count = orderMapper.selectPurchaseCount(tPurchasePro.getSkuId(), today.plusDays(1), today);
                        log.info("data---count:{}", count);
                        tPurchasePro.setPurchaseVolume(count);
                    } catch (Exception ex) {
                        log.error("计算方式异常==》", ex);
                    }
                    try {
                        if (tPurchasePro.getPurchaseVolume() == null) {
                            tPurchasePro.setPurchaseVolume(0);
                        }
                        purchaseVolume += tPurchasePro.getPurchaseVolume();
                        purchasePrice = purchasePrice.add(tPurchasePro.getPurchasePrice().multiply(new BigDecimal(tPurchasePro.getPurchaseVolume())));
                    } catch (Exception ex) {
                        log.error("", ex);
                        log.info("generate-error:{}", JSON.toJSONString(tPurchasePro));
                    }
//                    }
                }
                TPurchaseOrder tPurchaseOrder = new TPurchaseOrder();
                tPurchaseOrder.setSupplierName(tPurchaseProList.get(0).getSupplierName());
                tPurchaseOrder.setSupplierId(tPurchaseProList.get(0).getSupplierId());
                tPurchaseOrder.setWarehouseId(tPurchaseProList.get(0).getWarehouseId());
                tPurchaseOrder.setWarehouseName(tPurchaseProList.get(0).getWarehouseName());
                tPurchaseOrder.setPurchasePrice(purchasePrice);
                tPurchaseOrder.setPurchaseVolume(purchaseVolume);
                tPurchaseOrder.setCreateBy(1);
                tPurchaseOrder.setDeleted(0);
                genAsnAndPo(tPurchaseProList, tPurchaseOrder, userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void genNewPo(TPurchaseOrderHeadDto tPurchaseOrderHeadDto, Integer userId) {
        try {
            if (ListUtil.isNotEmpty(tPurchaseOrderHeadDto.getTPurchaseOrderDetailDtoList())) {
                Warehouse warehouse = warehouseMapper.selectById(tPurchaseOrderHeadDto.getWarehouse1());
                TSupplierInfo tSupplierInfo = tSupplierInfoMapper.selectById(tPurchaseOrderHeadDto.getSupplier1());
                TPurchaseOrder tPurchaseOrder = new TPurchaseOrder();
                tPurchaseOrder.setSupplierName(tPurchaseOrderHeadDto.getTPurchaseOrderDetailDtoList().get(0).getSupplierName());
                tPurchaseOrder.setCityId(tPurchaseOrderHeadDto.getCity1());
                tPurchaseOrder.setIsDirectWarehousingStr(tPurchaseOrderHeadDto.getIsDirectWarehousingStr());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (tPurchaseOrderHeadDto.getArrivalTime() != null) {
                    tPurchaseOrder.setArrivalTime(formatter.parse(tPurchaseOrderHeadDto.getArrivalTime()));
                }
                tPurchaseOrder.setRemark(tPurchaseOrderHeadDto.getRemark());
                tPurchaseOrder.setSupplierId(tPurchaseOrderHeadDto.getSupplier1());
                tPurchaseOrder.setWarehouseId(tPurchaseOrderHeadDto.getWarehouse1());
                if (warehouse != null) {
                    tPurchaseOrder.setWarehouseName(warehouse.getWarehouseName());
                }
                if (tSupplierInfo != null) {
                    tPurchaseOrder.setSupplierName(tSupplierInfo.getSupplierName());
                }
                int purchaseVolume = 0;
                BigDecimal purchasePrice = new BigDecimal(0);
                for (TPurchasePro tPurchasePro : tPurchaseOrderHeadDto.getTPurchaseOrderDetailDtoList()) {
                    if (tPurchasePro.getPurchaseVolume() != null && tPurchasePro.getPurchasePrice() != null) {
                        purchaseVolume += tPurchasePro.getPurchaseVolume();
                        purchasePrice = purchasePrice.add(tPurchasePro.getPurchasePrice().multiply(new BigDecimal(tPurchasePro.getPurchaseVolume())));
                        tPurchasePro.setWarehouseId(tPurchaseOrderHeadDto.getWarehouse1());
                    }
                }
                if (tPurchaseOrderHeadDto.getIsDirectWarehousingStr() != null && tPurchaseOrderHeadDto.getIsDirectWarehousingStr()) {
                    tPurchaseOrder.setState(OrderState.ORDER_STATE_5.getIndex());
                }
                tPurchaseOrder.setPurchaseVolume(purchaseVolume);
                tPurchaseOrder.setPurchasePrice(purchasePrice);
                tPurchaseOrder.setCreateBy(1);
                tPurchaseOrder.setDeleted(0);
                genAsnAndPo(tPurchaseOrderHeadDto.getTPurchaseOrderDetailDtoList(), tPurchaseOrder, userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void syncProFromClp(TSupplierClPro clPro) {
        genProFromOrder4NewOrder(clPro);
    }

    private boolean genProFromOrder4NewOrder(TSupplierClPro clPro) {
        boolean flag = false;
        try {
            if (clPro.getSkuId() == null) {
                return flag;
            }
            QueryWrapper<TPurchasePro> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sku_id", clPro.getSkuId());
            LocalDateTime now = LocalDateTime.now();
            if (now.getHour() > 23) {
                queryWrapper.gt("create_time", TimerUtil.getcurrent23Date());
            } else {
                queryWrapper.gt("create_time", TimerUtil.getLast23Date());
            }
            queryWrapper.last(" limit 1");
            TPurchasePro tPurchasePro = tPurchaseProMapper.selectOne(queryWrapper);
            if (tPurchasePro != null) {                    // 如果有就更新商品数据
                TPurchasePro updateDo = new TPurchasePro();
                updateDo.setId(tPurchasePro.getId());
                if (tPurchasePro.getPurchaseVolume() != null && clPro.getPurchaseVolume() != null) {
                    updateDo.setPurchaseVolume(tPurchasePro.getPurchaseVolume() + clPro.getPurchaseVolume());
                }
                updateDo.setSkuName(clPro.getSkuName());
                updateDo.setSkuUnit(clPro.getSkuUnit());

                Sku sku = skuMapper.selectById(clPro.getSkuId());
                if (sku != null) {
                    Spu spu = spuMapper.selectById(sku.getSpuId());
                    if (spu != null) {
                        updateDo.setOrigin(spu.getOrigin());
                        updateDo.setDateDue(clPro.getDateDue());
                        updateDo.setDateProduce(clPro.getDateProduce());
                    }
                    updateDo.setBarcode(sku.getBarcode());
                }
                if (sku.getDimensionValues() != null) {
                    updateDo.setDimensionValues(sku.getDimensionValues().toJSONString());
                }
                tPurchaseProMapper.updateById(updateDo);

                // 创建采购信息汇总
//                if(clPro.getPurchaseVolume() != null && clPro.getPurchaseVolume() > 0) {
//                    createPurchaseInfo(tPurchasePro);
//                }
            } else {
                TPurchasePro insertDo = new TPurchasePro();
                BeanUtils.copyProperties(clPro, insertDo);
                tPurchaseProMapper.insert(insertDo);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;

    }

    @Override
    public void genPo(TPurchaseOrder tPurchaseOrder) {
        QueryWrapper<TPurchasePro> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_id", tPurchaseOrder.getSupplierId());
        queryWrapper.eq("sku_id", tPurchaseOrder.getSkuId());
        queryWrapper.ne("is_order", Constant.IS_ORDER_YES);
        List<TPurchasePro> tPurchasePros = tPurchaseProMapper.selectList(queryWrapper);
        if (ListUtil.isNotEmpty(tPurchasePros)) {
            genAsnAndPo(tPurchasePros, tPurchaseOrder, 1);
        }
    }

    public void genAsnAndPo(List<TPurchasePro> tPurchaseProList, TPurchaseOrder tPurchaseOrder, Integer userId) {
        log.info("======t_purchase_order : start ======{}:{}", JSON.toJSONString(tPurchaseProList), tPurchaseOrder);
        //生成po单
        genPo(tPurchaseProList, tPurchaseOrder);
        log.info("purchase-log::{}", JSON.toJSONString(tPurchaseOrder));
        if (tPurchaseOrder.getId() != null && tPurchaseOrder.getIsDirectWarehousingStr() != null && tPurchaseOrder.getIsDirectWarehousingStr()) {
            log.info("======genAsnByTPurchasePro : start ======");
            genAsnByTPurchasePro(tPurchaseProList, tPurchaseOrder, userId);
        }
    }

    private void genAsnByTPurchasePro(List<TPurchasePro> tPurchaseProList, TPurchaseOrder tPurchaseOrder, Integer userId) {
        AsnHeader asnHeader = new AsnHeader();
        asnHeader.setRefOrderId(tPurchaseOrder.getId());
        asnHeader.setAsnStatus(String.valueOf(tPurchaseOrder.getState()));
        asnHeader.setRefOrderCode(tPurchaseOrder.getOrderCode());
        asnHeader.setSupplierId(tPurchaseOrder.getSupplierId());
        asnHeader.setWarehouseId(tPurchaseOrder.getWarehouseId());
        if (tPurchaseOrder.getArrivalTime() != null) {
            asnHeader.setExptArriveTime(tPurchaseOrder.getArrivalTime());
        }
        asnHeader.setNote(tPurchaseOrder.getRemark());
        List<AsnDetail> asnDetailList = new ArrayList<>();
        try {
            if (ListUtil.isNullOrEmpty(tPurchaseProList)) {
                return;
            }
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            DateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日");
            tPurchaseProList.forEach(
                    item -> {
                        try {
                            if (item.getPurchaseVolume() == null || item.getPurchaseVolume() < 1) {
                                return;
                            }

                            AsnDetail asnDetail = new AsnDetail();
                            asnDetail.setWarehouseId(item.getWarehouseId());
                            asnDetail.setSkuId(item.getSkuId());
                            asnDetail.setSupplierId(item.getSupplierId());
                            if (item.getPurchaseVolume() != null) {
                                asnDetail.setPurchaseCount(new BigDecimal(item.getPurchaseVolume()));
                            } else {
                                asnDetail.setPurchaseCount(new BigDecimal(0));
                            }
                            asnDetail.setPrice(item.getPurchasePrice());
                            if (item.getDateProduce() != null) {
                                if (item.getDateProduce().contains(".")) {
                                    item.setDateProduce(item.getDateProduce().replaceAll(".", "-"));
                                }
                                try {
                                    asnDetail.setProductionDate(format.parse(item.getDateProduce()));
                                } catch (Exception ex) {
                                    try {
                                        asnDetail.setProductionDate(format1.parse(item.getDateProduce()));
                                    } catch (Exception e) {
                                        asnDetail.setProductionDate(new Date());
                                    }

                                }
                            }
                            if (item.getDateDue() != null) {
                                if (item.getDateDue().contains(".")) {
                                    item.setDateDue(item.getDateDue().replaceAll(".", "-"));
                                }
                                try {
                                    asnDetail.setExpirationDate(format.parse(item.getDateDue()));
                                } catch (Exception ex) {
                                    try {
                                        asnDetail.setExpirationDate(format1.parse(item.getDateDue()));
                                    } catch (Exception e) {
                                        asnDetail.setExpirationDate(new Date());
                                    }

                                }
                            }
                            asnDetailList.add(asnDetail);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
            );

            wmsReceiveFacade.addAsnByPms(asnHeader, asnDetailList, tPurchaseOrder.getWarehouseId(), userId.intValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void genAsn(List<TPurchaseOrderDetail> tPurchaseProList, TPurchaseOrder tPurchaseOrder, TPurchaseSend tPurchaseSend, Integer userId) {
        AsnHeader asnHeader = new AsnHeader();
        asnHeader.setRefOrderId(tPurchaseOrder.getId());
        asnHeader.setRefOrderCode(tPurchaseOrder.getOrderCode());
        asnHeader.setAsnStatus(String.valueOf(tPurchaseOrder.getState()));
        asnHeader.setSupplierId(tPurchaseOrder.getSupplierId());
        asnHeader.setWarehouseId(tPurchaseOrder.getWarehouseId());
        if (tPurchaseOrder.getArrivalTime() != null) {
            asnHeader.setExptArriveTime(tPurchaseOrder.getArrivalTime());
        }
        asnHeader.setNote(tPurchaseOrder.getRemark());
        if (tPurchaseSend != null) {
            asnHeader.setCarNo(tPurchaseSend.getSendCar());
            asnHeader.setTel(tPurchaseSend.getCarMobile());
            asnHeader.setConcatName(tPurchaseSend.getCarDriver());
        }
        List<AsnDetail> asnDetailList = new ArrayList<>();
        try {
            if (ListUtil.isNullOrEmpty(tPurchaseProList)) {
                return;
            }
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            tPurchaseProList.forEach(
                    item -> {
                        if (item.getPurchaseVolume() == null || item.getPurchaseVolume() < 1) {
                            return;
                        }
                        try {
                            AsnDetail asnDetail = new AsnDetail();
                            asnDetail.setWarehouseId(item.getWarehouseId());
                            asnDetail.setSupplierId(item.getSupplierId());
                            asnDetail.setSkuId(item.getSkuId());
                            asnDetail.setPurchaseCount(new BigDecimal(item.getPurchaseVolume()));
                            asnDetail.setPrice(item.getPurchasePrice());
                            if (item.getDateProduce() != null) {
                                if (item.getDateProduce().contains(".")) {
                                    item.setDateProduce(item.getDateProduce().replaceAll(".", "-"));
                                }
                                asnDetail.setProductionDate(format.parse(item.getDateProduce()));
                            }
                            if (item.getDateDue() != null) {
                                if (item.getDateDue().contains(".")) {
                                    item.setDateDue(item.getDateDue().replaceAll(".", "-"));
                                }
                                asnDetail.setExpirationDate(format.parse(item.getDateDue()));
                            }
                            asnDetailList.add(asnDetail);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
            );

            wmsReceiveFacade.addAsnByPms(asnHeader, asnDetailList, tPurchaseOrder.getWarehouseId(), userId.intValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void genPo(List<TPurchasePro> tPurchasePros, TPurchaseOrder tPurchaseOrder) {
        TPurchaseOrder inOrderDo = new TPurchaseOrder();
        BeanUtils.copyProperties(tPurchaseOrder, inOrderDo);
        if (tPurchaseOrder.getIsDirectWarehousingStr() != null && tPurchaseOrder.getIsDirectWarehousingStr()) {
            inOrderDo.setState(OrderState.ORDER_STATE_5.getIndex());
        } else {
            inOrderDo.setState(OrderState.ORDER_STATE_0.getIndex());
        }
        inOrderDo.setOrderCode(Convert.getOrderCodeByTime());
        if (tPurchaseOrder.getIsDirectWarehousingStr() != null && tPurchaseOrder.getIsDirectWarehousingStr()) {
            inOrderDo.setIsDirectWarehousing(Constant.IS_ORDER_YES);
        } else {
            inOrderDo.setIsDirectWarehousing(Constant.IS_ORDER_NO);
        }

        int falseNum = 0;
        for (TPurchasePro item : tPurchasePros) {
            if (item.getPurchaseVolume() == null || item.getPurchaseVolume() < 1) {
                falseNum += 1;
                continue;
            }
            TPurchaseOrderDetail inOrderDetail = new TPurchaseOrderDetail();
            BeanUtils.copyProperties(item, inOrderDetail);
            inOrderDetail.setWarehouseName(tPurchaseOrder.getWarehouseName());
            // 判断是否完全满足库存,如果采购量大于库存,则下库存的量,让采购手动下单
            /**
             * TODO 直接订单全部下完。让供应商确认
             */
//            if (item.getPurchaseVolume() != null && item.getSupplyVolume() != null && item.getPurchaseVolume() > item.getSupplyVolume()) {
//                inOrderDetail.setPurchaseVolume(item.getSupplyVolume());
//            }
            inOrderDetail.setParentOrderCode(inOrderDo.getOrderCode());
            setBarCodeAndOrign(inOrderDetail, item.getSkuId());
            inOrderDetail.setCreateTime(new Date());
            inOrderDetail.setUpdateTime(new Date());
            tPurchaseOrderDetailMapper.insert(inOrderDetail);
            log.info("insert-detail-purchase:{}", JSON.toJSONString(inOrderDetail));

            TPurchasePro updateDo = new TPurchasePro();
            updateDo.setId(item.getId());

//            // 判断是否完全满足库存
//            if (item.getPurchaseVolume() != null && item.getSupplyVolume() != null && item.getPurchaseVolume() > item.getSupplyVolume()) {
//                updateDo.setIsMissingParts(Constant.IS_MISSING_PARTS_YES);
//                updateDo.setMissingPartsVolume(item.getPurchaseVolume() - item.getSupplyVolume());
//                updateDo.setPurchaseVolume(item.getPurchaseVolume() - item.getSupplyVolume());
//                updateDo.setIsOrder(Constant.IS_ORDER_NO);
//            } else {
            updateDo.setPurchaseVolume(0);
            updateDo.setIsOrder(Constant.IS_ORDER_YES);
//            }
            updateDo.setUpdateTime(new Date());
            tPurchaseProMapper.updateById(updateDo);

            // 新建的订单 汇总到 采购信息汇总
            if (item.getPurchaseVolume() != null && item.getPurchaseVolume() > 0) {
                createPurchaseInfo(item);
            }
        }

        TSupplierInfo tSupplierInfo = tSupplierInfoMapper.selectById(tPurchaseOrder.getSupplierId());
        if (tSupplierInfo != null) {
            inOrderDo.setSupplierMobile(tSupplierInfo.getMobile());
        }
        inOrderDo.setDeleted(0);
        if (falseNum == tPurchasePros.size()) {
            return;
        }
        inOrderDo.setCreateTime(new Date());
        inOrderDo.setUpdateTime(new Date());
        log.info("insert t_purchase_order:{}", JSON.toJSONString(inOrderDo));
        tPurchaseOrderMapper.insert(inOrderDo);
        tPurchaseOrder.setId(inOrderDo.getId());
        tPurchaseOrder.setOrderCode(inOrderDo.getOrderCode());

    }

    private void setBarCodeAndOrign(TPurchaseOrderDetail inOrderDetail, Long skuId) {
        Sku sku = skuMapper.selectById(skuId);
        if (sku != null) {
            Spu spu = spuMapper.selectById(sku.getSpuId());
            if (spu != null) {
                inOrderDetail.setOrigin(spu.getOrigin());
            }
            inOrderDetail.setBarcode(sku.getBarcode());
        }
    }

    @Override
    public List<TKV> getWareHouse(Long supplierId) {
        if (supplierId == null) {
            return null;
        }
        QueryWrapper<TSupplierClassification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_id", supplierId);
        TSupplierClassification tSupplierClassification = tSupplierClassificationMapper.selectOne(queryWrapper);
        if (tSupplierClassification.getWarehouse() == null) {
            return null;
        }

        QueryWrapper<Warehouse> warehouseQueryWrapper = new QueryWrapper<>();

        List<String> wareHouseIds = Convert.json2list(tSupplierClassification.getWarehouse());
        warehouseQueryWrapper.in("id", wareHouseIds);

        List<Warehouse> warehouseList = warehouseMapper.selectList(warehouseQueryWrapper);
        if (ListUtil.isNullOrEmpty(warehouseList)) {
            return null;
        }
        List<Warehouse> warehouses = warehouseList.stream().collect(collectingAndThen(
                toCollection(() -> new TreeSet<>(comparing(n -> n.getId()))), ArrayList::new)
        );

        return Convert2KV.WareHouse2kv(warehouses);
    }

    @Override
    public void editSupplier(TPurchasePro tPurchasePro) {
        try {
            TPurchasePro updateDo = new TPurchasePro();
            updateDo.setId(tPurchasePro.getId());
            updateDo.setSupplierId(tPurchasePro.getSupplierId());
            updateDo.setSupplierName(tPurchasePro.getSupplierName());
            updateDo.setSupplyVolume(tPurchasePro.getSupplyVolume());
            updateDo.setSupplierPrice(tPurchasePro.getSupplierPrice());
            updateDo.setSupplyVolume(tPurchasePro.getSupplyVolume());
            if (tPurchasePro.getWareHouseIds() != null) {
                // 获取供应商的仓库信息
                Warehouse warehouse = warehouseMapper.selectById(Long.valueOf(tPurchasePro.getWareHouseIds()));
                if (warehouse != null) {
                    updateDo.setWarehouseName(warehouse.getWarehouseName());
                    updateDo.
                            setWarehouseId(warehouse.getId());
                }
            }
            tPurchaseProMapper.updateById(updateDo);

            if (tPurchasePro.getPurchaseVolume() != null && tPurchasePro.getPurchaseVolume() > 0) {
                createPurchaseInfo(updateDo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void editSupplierByRecord(TPurchasePro tPurchasePro) {
        try {
            if (tPurchasePro.getWareHouseIds() != null) {
                // 获取供应商的仓库信息
                Warehouse warehouse = warehouseMapper.selectById(Long.valueOf(tPurchasePro.getWareHouseIds()));
                if (warehouse != null) {
                    tPurchaseProMapper.updatePurchaseProFromRecord(tPurchasePro.getSkuId(), tPurchasePro.getSupplierId(), tPurchasePro.getSupplierName(), Long.valueOf(tPurchasePro.getWareHouseIds()), warehouse.getWarehouseName(), tPurchasePro.getSupplierPrice(), tPurchasePro.getSupplyVolume());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<TPurchasePro> getBySupplierId(Long headerId) {
        QueryWrapper<TPurchasePro> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_id", headerId);
        List<TPurchasePro> tPurchasePros = tPurchaseProMapper.selectList(queryWrapper);
        return tPurchasePros;
    }


    @Override
    public void updatePurchaseProFromClp(Long skuId, BigDecimal supplierPrice, Integer supplyVolume) {
        if (skuId == null || supplierPrice == null) {
            return;
        }
        tPurchaseProMapper.updatePurchaseProFromClp(skuId, supplierPrice, supplyVolume);
    }

    @Override
    public void syncProAndClp(TPurchaseProDto tPurchaseProDto) {
        if (tPurchaseProDto.getSkuId() == null) {
            return;
        }
        try {
            Sku sku = skuMapper.selectAllSkuStatus(tPurchaseProDto.getSkuId());
            log.error("TPurchaseProServiceImpl-syncProAndClp-skuId:" + sku.getId());
            if (sku != null && sku.getDeleted().equals(1)) {
                QueryWrapper<TPurchasePro> deletePro = new QueryWrapper<>();
                deletePro.eq("sku_id", tPurchaseProDto.getSkuId());
                tPurchaseProMapper.delete(deletePro);

                QueryWrapper<TSupplierClPro> deleteClp = new QueryWrapper<>();
                deleteClp.eq("sku_id", tPurchaseProDto.getSkuId());
                tSupplierClProMapper.delete(deleteClp);
                log.error("TPurchaseProServiceImpl-syncProAndClp-delete-success:" + sku.getId());
            } else {
                Spu spu = spuMapper.selectById(sku.getSpuId());
                if (spu != null) {
                    String dimensionValues = "[]";
                    if (sku.getDimensionValues() != null) {
                        dimensionValues = sku.getDimensionValues().toJSONString();
                    }
                    tPurchaseProMapper.updatePurchaseProFromSku(sku.getId(), spu.getSpuName(), dimensionValues, spu.getOrderSpecUnit(), spu.getDateProduce(), sku.getBarcode(), spu.getDateDue(), spu.getOrigin());

                    tSupplierClProMapper.updateClpFromSku(sku.getId(), spu.getSpuName(), dimensionValues, spu.getOrderSpecUnit(), spu.getDateProduce(), spu.getDateDue());
                    log.error("TPurchaseProServiceImpl-syncProAndClp-update-success:" + sku.getId());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
